#include "threadpool.h"
int exitPipe[2];

void handler(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"exit",4);
}

int main(int argc, char *argv[])
{
    // ./server 192.168.153.129 55555
    ARGS_CHECK(argc,3);
    pipe(exitPipe);
    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("process exit\n");
        return 0;
    }
    close(exitPipe[1]);
    threadPool_t pool;
    memset(&pool,0,sizeof(pool));
    thread_pool_init(&pool);
    make_worker(&pool);

    int sockfd = tcp_init(argv[1],argv[2]);
    int epfd = epoll_create(1);
    epoll_add(epfd,sockfd);
    epoll_add(epfd,exitPipe[0]);
    struct epoll_event readyset[1];

    int netfd = -1;
    
    while(1){
        epoll_wait(epfd,readyset,1,-1);
        if(readyset->data.fd == sockfd){
            netfd = accept(sockfd,NULL,NULL);
            pthread_mutex_lock(&pool.mutex);
            enqueue(&pool.taskQueue,netfd);
            pthread_cond_broadcast(&pool.cond);
            pthread_mutex_unlock(&pool.mutex);
        }
        else if(readyset->data.fd == exitPipe[0]){
            pthread_mutex_lock(&pool.mutex);
            pool.exitFlag = 1;
            pthread_cond_broadcast(&pool.cond);
            pthread_mutex_unlock(&pool.mutex);

            for(int i = 0; i < pool.threadNum; i++){
                pthread_join(pool.childThreadSet[i],NULL);
                printf("thread exit\n");
            }
            return 0;
        }
    }
    return 0;
}

